<template>
  <div>
    <el-card>
      <span>胡帅</span>
      <el-form :inline="true">
        <!-- 搜索+按钮 -->
        <el-form-item>
          <el-input v-model="input" placeholder="根据用户名搜索"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button size="mini" @click="clearInput" >清空</el-button>
          <el-button size="mini" type="primary" @click="searchInput" >搜索</el-button>
        </el-form-item>
        <el-form-item style="float:right">
          <el-button  size="mini" type="success" icon="el-icon-edit" @click="showDialog">新增权限组</el-button>
        </el-form-item>
        <el-alert type="info" :closable="false">
          <!-- 记录栏 -->
          <template>
            <i class="el-icon-info"></i>
            共{{ dataInfo }}条记录
          </template>
        </el-alert>
        <!-- 表格 -->
        <template>
          <el-table
            :data="userInfo"
            :header-cell-style="{textAlign: 'center'}"
            :cell-style="{ textAlign: 'center' }"
            style="width: 100%">
            <el-table-column
              type="selection"
              width="180">
            </el-table-column>
            <el-table-column
              prop="title"
              label="用户名"
              width="180">
            </el-table-column>
            <el-table-column label="日期">
              <template v-slot='{ row }'>{{ row.create_date }}</template>
            </el-table-column>
            <el-table-column label="操作">
              <template v-slot='{ row }'>
                <el-button @click="edit(row)" class="skyblue" type="primary" icon="el-icon-edit" circle></el-button>
                <el-button @click="del(row)" class="red"  type="danger" icon="el-icon-delete" circle></el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-form>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="tableItem.pagesize"
        layout="sizes, prev, pager, next, jumper"
        style="margin:20px 0; float:right"
        background
        :total="dataInfo">
      </el-pagination>
    </el-card>
    <!-- 对话框 -->
    <el-dialog
      title="提示"
      :visible="dialogVisible"
      width="50%"
      @close='onClose'
      >
      <el-form
      ref="formBase"
      :rules="rules"
      :model="formBase"
      label-width="100px"
      style="width:450px;margin:auto"
      >
        <el-form-item label="用户名" prop="title">
          <el-input  v-model.trim="formBase.title"></el-input>
        </el-form-item>
        <el-form-item label="权限分配">
          <el-tree
            :data="treeData"
            show-checkbox
            node-key="id"
            ref="tree"
            :default-expanded-keys="[0]"
            :default-checked-keys="formBase.permissions"
            :props="defaultProps"
            >
          </el-tree>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="onClose">取 消</el-button>
        <el-button type="primary" @click="onSave">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { list as menusList } from '@/api/base/menus.js'
import { timeFilter } from '@/filters'
import { list, add, detail, update, remove } from '@/api/base/permissions.js'
let _this = []
export default {
  name: 'permissions',
  data () {
    return {
      input: '',
      userInfo: [],
      userInfoItem: [],
      tableItem: {
        page: 1,
        pagesize: 10,
        keyword: '',
        disabled: 1
      },
      currentPage: 1,
      dialogVisible: false,
      rules: {
        title: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      },
      count: 1,
      treeList: [],
      defaultProps: {
        label: 'title'
      },
      formBase: {
        title: '',
        permissions: []
      },
      dataInfo: null
    }
  },
  computed: {
    treeData () {
      function createNode (item) {
        // 复选框选择
        let checked = false
        let selected = false
        if (_this !== null && _this.formBase.permissions.length > 0) {
          const per = _this.formBase.permissions.find(function (value, index) {
            return value === item.id
          })
          selected = !!per
        }
        // 标记勾选
        if (selected) {
          const isPoint = item.childs === undefined && item.points === undefined
          const hasChilds = item.childs !== undefined && item.childs.length > 0
          const hasPoints = item.points !== undefined && item.points.length > 0
          if (isPoint) {
            checked = true
          } else if (hasPoints) {
            checked = false
          } else if (hasChilds) {
            checked = false
          } else {
            checked = true
          }
        }
        return {
          id: item.id === undefined ? 0 : item.id,
          title: item.title,
          children: [],
          selected: selected,
          checked: checked
        }
      }
      function parseNodes (nodes, parentNode) {
        for (const it of nodes) {
          const node = createNode(it)
          // 标记选中
          // console.log(node.checked)
          if (node.checked) {
            parentNode.selected = true
          }
          if (it.childs !== undefined && it.childs.length > 0) {
            parseNodes(it.childs, node)
          } else if (it.points !== undefined && it.points.length > 0) {
            parseNodes(it.points, node)
          }
          parentNode.children.push(node)
        }
      }
      const nodes = createNode({ title: '系统菜单和页面权限点', expand: true })
      parseNodes(this.treeList, nodes)
      return [nodes]
    }
  },

  created () {
    _this = this
    this.loadList()
    this.loadmenus()
  },

  methods: {
    // 获取权限列表
    async loadList () {
      const res = await list(this.tableItem)
      // console.log(res.data.list)
      // console.log(res)
      this.userInfo = res.data.list
      this.userInfoItem = res.data
      this.dataInfo = res.data.counts
      // console.log(this.userInfoItem)
      // 通过map遍历再利用时间过滤器
      this.userInfo.map(item => {
        // console.log(item.last_update_time)
        item.create_date = timeFilter(item.create_date)
        return item
      })
      // console.log(this.userInfo)
    },
    // 清空按钮
    clearInput () {
      this.input = ''
      this.loadList()
    },
    // 搜索按钮
    searchInput () {
      if (this.input === '') {
        return this.userInfo
      } else {
        const res = this.userInfo.filter(item => {
          return item.title.indexOf(this.input) !== -1
        })
        this.userInfo = res
        this.dataInfo = res.length
      }
    },
    // 点击显示对话框
    showDialog () {
      this.formBase = {
        title: '',
        permissions: []
      }
      this.dialogVisible = true
    },
    // 获取权限
    async loadmenus () {
      const res = await menusList()
      // console.log(res)
      this.treeList = res.data
      // console.log(this.treeList)
    },
    // 确定
    async onSave () {
      this.$refs.formBase.validate()
      const res = this.$refs.tree.getCheckedKeys()
      this.formBase.permissions = res
      // console.log(res)
      try {
        if (this.formBase.id) {
          await update(this.formBase)
          this.$message.success('编辑成功')
        } else {
          await add(this.formBase)
          this.$message.success('添加成功')
        }
        this.dialogVisible = false
        this.formBase = {
          title: '',
          permissions: []
        }
        this.loadList()
      } catch (err) {
        this.$message.error('添加失败')
      }
    },
    onClose () {
      this.$refs.formBase.resetFields()
      this.dialogVisible = false
    },
    async edit (row) {
      // this.formBase = row
      const res = await detail(row)
      // console.log(res.data)
      this.formBase = res.data
      this.dialogVisible = true
    },
    // 删除按钮
    async del (row) {
      this.$confirm('此操作将永久删除用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await remove(row)
        this.$message.success('删除成功')
        const totalPage = Math.ceil((this.dataInfo - 1) / this.tableItem.pagesize)
        const currentPage = this.tableItem.page > totalPage ? totalPage : this.tableItem.page
        this.tableItem.page = this.tableItem.page < 1 ? 1 : currentPage
        this.loadList()
      }).catch(() => {})
    },

    // 分页
    handleSizeChange (val) {
      // console.log(val)
      this.tableItem.pagesize = val
      this.loadList()
    },
    handleCurrentChange (val) {
      // console.log(val)
      this.tableItem.page = val
      this.loadList()
    }
  }
}
</script>

<style scoped lang='less'>
/deep/.el-card{
  margin: 20px !important;
}
.skyblue{
  background-color: rgb(236, 245, 255,0.3);
  border-color: rgb(167, 212, 238,0.3);
  color: rgb(64, 158, 255);
  &:hover{
  background-color: rgb(64, 158, 255);
  border-color: rgb(64, 158, 255);
  color: #fff;
  }
}
.red{
  background-color: rgb(254, 240, 240,0.3);
  border-color: rgb(252, 206, 206,0.3);
  color: rgb(245, 123, 120);
  &:hover{
  background-color: rgb(245, 108, 108);
  border-color: rgb(245, 108, 108);
  color: #fff;
  }
}
</style>
